/*
 * @Author: lihaogn
 * @Date: 2021-12-13 13:57:02
 * @LastEditTime: 2021-12-23 11:03:07
 * @LastEditor: lihaogn
 * @Description: 通用工具函数
 * @FilePath: \lix-admin-server\app\utils\commonUtils.js
 */
/**
 * @author: lihaogn
 * @Date: 2021-12-12 15:07:22
 * @description: 生成日期字符串（14位字符）
 * @param {*}
 * @return {*} '20211212150624'
 */
function formatDateTime() {
  const date = new Date();

  const y = date.getFullYear() + "";
  let m = date.getMonth() + 1;
  m = m < 10 ? "0" + m : m;
  let d = date.getDate();
  d = d < 10 ? "0" + d : d;
  let h = date.getHours();
  h = h < 10 ? "0" + h : h;
  let minute = date.getMinutes();
  minute = minute < 10 ? "0" + minute : minute;
  let second = date.getSeconds();
  second = second < 10 ? "0" + second : second;

  return y + m + d + h + minute + second;
}
/**
 * @author: lihaogn
 * @Date: 2021-12-12 14:58:40
 * @description: 产生随机4位字符
 * @param {*}
 * @return {*}
 */
function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

/**
 * @author: lihaogn
 * @Date: 2021-12-12 15:01:46
 * @description: 产生随机 36 位字符
 * @param {*}
 * @return {*}
 */
const getUUID = () => {
  return formatDateTime() + "-" + S4() + S4() + "-" + S4() + S4() + S4();
};

/**
 * @author: lihaogn
 * @Date: 2021-12-12 15:11:58
 * @description: 生成随机的用户名
 * @param {*}
 * @return {*} 返回20位随机字符
 */
const getUsername = () => {
  let name = "";
  for (let index = 0; index < 20; index++) {
    name += String.fromCharCode(Math.random() * 94 + 33);
  }

  return name;
};

/**
 * @author: lihaogn
 * @Date: 2021-12-20 11:29:15
 * @description: arr 生成 tree
 * @param {*}
 * @return {*}
 */
const makeTree = (arr) => {
  const res = [];
  if (arr.length) {
    arr.forEach((item) => {
      if (
        item.parentId === null ||
        item.parentId === undefined ||
        item.parentId === ""
      ) {
        res.push(item);
      } else {
        const parentItem = arr.find((x) => x.id === item.parentId);
        if (parentItem) {
          parentItem.dataValues.children
            ? parentItem.dataValues.children.push(item)
            : (parentItem.dataValues.children = [item]);
        }
      }
    });
  }

  return res;
};

module.exports = { getUUID, getUsername, makeTree };
